﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Common;
using Fasterflect;

namespace ShahyadS.BuildInspectorVSPackage
{
	public static class BaseHierarchyNodeExtentions
	{
		public static List<T> GetChildNodesRecursively<T>(this BaseHierarchyNode node) where T : BaseHierarchyNode
		{
			List<T> allNodes = new List<T>();
			BaseHierarchyNode child1 = node.FirstChild;
			while (child1 != null)
			{
				var expand = child1.IsExpanded;
				if (!expand && child1.GetType().Name != "ProjectNode")
				{
					child1.Expand(true);
				}
				if (child1 is T)
					allNodes.Add((T)child1);
				allNodes.AddRange(child1.GetChildNodesRecursively<T>());
				if (!expand && child1.GetType().Name != "ProjectNode")
				{
					child1.Expand(false);
				}
				child1 = child1.NextSibling;
			}
			var nestedTree = node.NestedHierarchy;
			if (nestedTree != null)
			{
				var nestedTreeHierarchyNode = nestedTree.GetPropertyValue("HierarchyNode") as BaseHierarchyNode;
				if (nestedTreeHierarchyNode != null)
				{
					var expand2 = nestedTreeHierarchyNode.IsExpanded;
					if (!expand2 && nestedTreeHierarchyNode.GetType().Name != "ProjectNode")
					{
						nestedTreeHierarchyNode.Expand(true);
					}
					allNodes.AddRange(nestedTreeHierarchyNode.GetChildNodesRecursively<T>());
					if (!expand2 && nestedTreeHierarchyNode.GetType().Name != "ProjectNode")
					{
						nestedTreeHierarchyNode.Expand(false);
					}
				}
			}
			return allNodes;
		}
	}
}
